package com.leimo.config;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;

/**
 * 微信开方平台配置
 *
 * @author 段誉
 * @create 2019-04-19 13:46
 */
@Configuration
@EnableConfigurationProperties(WechatProperties.class)
public class WechatConfig {
  private WechatProperties properties;

  @Autowired
  public WechatConfig(WechatProperties properties) {
    this.properties = properties;
  }

  /**
   * @desc 微信公众平台服务类配置
   * @Author 段誉
   * @Date 2019/4/19 15:01
   * @method
   */
  @Bean
  public WxMpService wxMpService(WxMpConfigStorage wxMpConfigStorage) {
    WxMpService wxMpService = new WxMpServiceImpl();
    wxMpService.setWxMpConfigStorage(wxMpConfigStorage);
    return wxMpService;
  }

  /**
   * @desc 微信公众号平台配置
   * @Author 段誉
   * @Date 2019/4/19 14:57
   * @method
   */
  @Bean
  public WxMpConfigStorage wxMpConfigStorage() {
    WxMpInMemoryConfigStorage storage = new WxMpInMemoryConfigStorage();
    storage.setAppId(properties.getAppId());
    storage.setSecret(properties.getAppSecret());
    return storage;
  }

  /**
   * @desc 注入微信支付服务类
   * 后边如果需要应对微信冗灾可以将自己重写WxPayServiceApacheHttpImpl，WxPayServiceImpl，BaseWxPayServiceImpl
   * @Author 段誉
   * @Date 2019/4/19 14:59
   * @method
   */
  @Bean
  public WxPayService wxPayService(WxPayConfig wxPayConfig) {
    WxPayService wxPayService = new WxPayServiceImpl();
    wxPayService.setConfig(wxPayConfig);
    return wxPayService;
  }

  /**
   * @desc 微信支付相关配置
   * @Author 段誉
   * @Date 2019/4/19 14:57
   * @method
   */
  @Bean
  public WxPayConfig wxPayConfig() {
    WxPayConfig payConfig = new WxPayConfig();
    payConfig.setAppId(StringUtils.trimToNull(properties.getAppId()));
    payConfig.setMchId(StringUtils.trimToNull(properties.getMchId()));
    payConfig.setMchKey(StringUtils.trimToNull(properties.getMchKey()));
    payConfig.setKeyPath(StringUtils.trimToNull(properties.getKeyPath()));
    return payConfig;
  }

}
